//
//  WH_NewestViewController.m
//  App_6.23
//
//  Created by wanghao on 16/6/24.
//  Copyright © 2016年 wanghao. All rights reserved.
//

#import "WH_NewestViewController.h"
#import "WH_HomeDetailController.h"
#import "WH_Home.h"
#import "WH_NewDetailViewController.h"
#import "WH_NewOneCell.h"
#import "TimeModel.h"

@interface WH_NewestViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>

@property (nonatomic, strong) UICollectionView  *myCollectionV;
@property (nonatomic, strong) NSMutableArray    *dataArr;
@property (nonatomic, strong) NSMutableArray    *datArrOne;
@property (nonatomic, assign) NSInteger          page;
@property (nonatomic, assign) BOOL              isUploading;
@property (nonatomic, strong) NSTimer           *m_timer;
@property (nonatomic, strong) NSMutableArray    *m_dataArray;

@end

@implementation WH_NewestViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"最新揭晓";
    //************初始化*************
    self.dataArr = [NSMutableArray array];
    self.datArrOne = [NSMutableArray array];
    self.m_dataArray = [NSMutableArray array];
    self.navigationItem.leftBarButtonItem = nil;
    self.isUploading = YES;
    self.page = 1;
    [self createCollection];
    [self postLottery];
    //[self postData];
    [self createTimer];
    [self registerNSNotificationCenter];
    [self createHub];
    [self hubShow];

}
#pragma mark - 创建CollectionView

-(void)createCollection{
    
    UICollectionViewFlowLayout *flowlayout = [[UICollectionViewFlowLayout alloc] init];
    //设置item 与四周的边界的距离 上左下右
    flowlayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    
    //设置每个itm大小
    flowlayout.itemSize = CGSizeMake(self.view.bounds.size.width/2, SCREEN_WIDTH/2 + 120);
    flowlayout.minimumLineSpacing = 0;
    flowlayout.minimumInteritemSpacing = 0;
    self.myCollectionV = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowlayout];
    self.myCollectionV.delegate = self;
    self.myCollectionV.dataSource = self;
    self.myCollectionV.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_myCollectionV];
    
    [self.myCollectionV registerClass:[WH_NewOneCell class] forCellWithReuseIdentifier:@"WH_NewOneCell"];

    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerTab)];
    self.myCollectionV.mj_header = header;
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerTab)];
    self.myCollectionV.mj_footer = footer;
    [self.myCollectionV.mj_footer setHidden:YES];

}
#pragma mark - 结束刷新

-(void)endFresh{
    
    [self hubDismiss];
    [self.myCollectionV.mj_footer endRefreshing];
    [self.myCollectionV.mj_header endRefreshing];
}
#pragma mark - 刷新&&加载

-(void)headerTab
{
    NSLog(@"下拉");
    self.page = 1;
    self.isUploading = NO;
    [self postLottery];

}
-(void)footerTab{
    
    self.isUploading = YES;
    self.page++;
    NSLog(@"%ld",(long)self.page);
    [self postData];
}
#pragma mark - 获取正在开奖数据 POST

-(void)postLottery{
    
    NSString *body = [NSString stringWithFormat:@"action=new_lottery&per_page=10"];
    
    [WH_AppTools postUrl:URLstr body:body result:HXJSON requestStyle:HXRequestString headerFile:nil success:^(id result) {
        if (self.isUploading == NO) {
            
            [self.datArrOne removeAllObjects];
            [self.m_dataArray removeAllObjects];

        }
       // NSLog(@"%@",result);
        NSDictionary *dic = result;
        NSArray *order_array = [dic objectForKey:@"order_array"];

        for (NSDictionary *dic in order_array) {
            
            WH_Home *newest = [WH_Home modelWithDictionary:dic];
            
            [self.datArrOne addObject:newest];
            NSString *timeCha = [WH_AppTools intervalFromLastDate:newest.cur_time toTheDate:newest.kaijang_time];
            [self.m_dataArray addObject:[TimeModel timeModelWithTime:[timeCha intValue]]];
        }
        [self postData];
        //[self endFresh];
        [self.myCollectionV reloadData];
        
    } failure:^(NSError *error) {
        
        
    }];
    
    
}
#pragma mark - 获取最新已开奖数据 POST

-(void)postData{
    
    
    NSString *body = [NSString stringWithFormat:@"action=new_win&page=%ld",(long)self.page];
    [WH_AppTools postUrl:URLstr body:body result:HXJSON requestStyle:HXRequestString headerFile:nil success:^(id result) {
        if (self.isUploading == NO) {
            
            [self.dataArr removeAllObjects];
        }
        if (_page == 1) {
            
            for (WH_Home *model in _datArrOne) {
                
                [_dataArr addObject:model];
                
            }

        }
        
        // NSLog(@"%@",result);
       
        NSDictionary *dic = result;
        NSArray *order_array = [dic objectForKey:@"order_array"];
        for (NSDictionary *dic in order_array) {
            
            WH_Home *newest = [WH_Home modelWithDictionary:dic];
            
            [self.dataArr addObject:newest];
            
        }
        [self.myCollectionV.mj_footer setHidden:NO];
        [self endFresh];
        [self hubDismiss];
        [self.myCollectionV reloadData];
    
    } failure:^(NSError *error) {
        
        
    }];
    
    
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.dataArr.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *newOne = @"WH_NewOneCell";
    WH_NewOneCell *cellOne = [collectionView dequeueReusableCellWithReuseIdentifier:newOne forIndexPath:indexPath];
    cellOne.newest = self.dataArr[indexPath.item];

    if (_m_dataArray.count > indexPath.row) {
        
        TimeModel * model = _m_dataArray[indexPath.row];
        [cellOne loadData:model indexPath:indexPath];
        
    }
    
    return cellOne;
    
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    WH_NewDetailViewController *newDetail = [[WH_NewDetailViewController alloc] init];
    
    WH_Home *newOne = self.dataArr[indexPath.row];
    newDetail.detailNew = newOne;
    if (_m_dataArray.count > indexPath.row) {
        
        newDetail.timeCount = self.m_dataArray[indexPath.row];
        
    }

    [self.navigationController pushViewController:newDetail animated:YES];

    
}
#pragma mark - 倒计时

- (void)createTimer {
    
    self.m_timer = [NSTimer timerWithTimeInterval:0.01 target:self selector:@selector(timerEvent) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_m_timer forMode:NSRunLoopCommonModes];
    //关闭定时器
    //[self.m_timer setFireDate:[NSDate distantFuture]];
    
    NSLog(@"关闭定时器");

}
- (void)timerEvent {
    
    for (int count = 0; count < _m_dataArray.count; count++) {
        
        TimeModel *model = _m_dataArray[count];
        [model countDown];
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_TIME_CELL object:nil];
    
}
#pragma mark - 通知中心
- (void)registerNSNotificationCenter {
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(notificationCenterEventFresh:)
                                                 name:NOTIFICATION_TIME_FRESH
                                               object:nil];
}

- (void)notificationCenterEventFresh:(id)obj{
    
    [self headerTab];
    NSLog(@"通知下拉刷新");

}
- (void)dealloc {
    
    NSLog(@"移除刷新通知");
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NOTIFICATION_TIME_FRESH object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
